package com.wang.gallerybackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.OriginalInfo;
import com.wang.gallerybackend.common.AjaxResult;
import com.wang.gallerybackend.config.CosClientConfig;
import com.wang.gallerybackend.exception.BusinessException;
import com.wang.gallerybackend.exception.ErrorCode;
import com.wang.gallerybackend.exception.ThrowUtils;
import com.wang.gallerybackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.Date;
import java.util.List;

@Deprecated
@Slf4j
@Service
public class FileManger {
	@Resource
	private CosClientConfig cosClientConfig;
	@Resource
	private CosManager cosManager;
	//允许文件上传的文件列表
	final List<String> ALLOW_FILE_SUFFIX = List.of("png", "jpg", "jpeg", "gif", "webp");
	final long MAXSIZE = 1024 * 1024 * 2;

	/**
	 * 上传图片
	 * @param multipartFile
	 * @param uploadPathPrefix
	 * @return
	 */
	public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
		//校验图片
		validPicture(multipartFile);
		//图片上传地址
		String uuid = RandomUtil.randomString(16);
		String originalFilename = multipartFile.getOriginalFilename();
		//自己拼接文件名
		String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),
				uuid, FileUtil.getSuffix(originalFilename));
		String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
		//解析结果并返回
		File file = null;
		try {
			file = File.createTempFile(uploadPath, null);
			multipartFile.transferTo(file);
			PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
			//获取图片信息对象
			ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
			//封装结果
			int picWidth = imageInfo.getWidth();
			int picHeight = imageInfo.getHeight();
			double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
			UploadPictureResult uploadPictureResult = new UploadPictureResult();
			uploadPictureResult.setUrl(cosClientConfig.getHost() + '/' + uploadPath);
			uploadPictureResult.setName(FileUtil.mainName(originalFilename));
			uploadPictureResult.setPicSize(FileUtil.size(file));
			uploadPictureResult.setPicWidth(picWidth);
			uploadPictureResult.setPicHeight(picHeight);
			uploadPictureResult.setPicScale(picScale);
			uploadPictureResult.setPicFormat(imageInfo.getFormat());
			//返回结果
			return uploadPictureResult;
		} catch (IOException e) {
			throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
		} finally {
			//临时文件清理
			deleteTemFile(file);
		}


	}

	/**
	 * 校验图片
	 * @param multipartFile
	 */
	private void validPicture(MultipartFile multipartFile) {

	}

	/**
	 * 删除临时文件
	 * @param file
	 */
	public static void deleteTemFile(File file) {
		if (file != null) {
			//删除临时文件
			boolean deleteResult = file.delete();
			if (!deleteResult) {
				log.error("文件删除失败 = {}", file.getAbsolutePath());
			}
		}
	}

	/**
	 * 通过url上传图片
	 * @param fileUrl
	 * @param uploadPathPrefix
	 * @return
	 */
	public UploadPictureResult uploadPictureByUrl(String fileUrl, String uploadPathPrefix) {
		//校验图片
		validPicture(fileUrl);
		//图片上传地址
		String uuid = RandomUtil.randomString(16);
		/*String originalFilename = multipartFile.getOriginalFilename();*/
		String originalFilename = FileUtil.mainName(fileUrl);
		//自己拼接文件名
		String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),
				uuid, FileUtil.getSuffix(originalFilename));
		String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
		//解析结果并返回
		File file = null;
		try {
			file = File.createTempFile(uploadPath, null);
			//下载图片
			HttpUtil.downloadFile(fileUrl, file);
/*
			multipartFile.transferTo(file);
*/
			PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
			//获取图片信息对象
			ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
			//封装结果
			int picWidth = imageInfo.getWidth();
			int picHeight = imageInfo.getHeight();
			double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
			UploadPictureResult uploadPictureResult = new UploadPictureResult();
			uploadPictureResult.setUrl(cosClientConfig.getHost() + '/' + uploadPath);
			uploadPictureResult.setName(FileUtil.mainName(originalFilename));
			uploadPictureResult.setPicSize(FileUtil.size(file));
			uploadPictureResult.setPicWidth(picWidth);
			uploadPictureResult.setPicHeight(picHeight);
			uploadPictureResult.setPicScale(picScale);
			uploadPictureResult.setPicFormat(imageInfo.getFormat());
			//返回结果
			return uploadPictureResult;
		} catch (IOException e) {
			throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
		} finally {
			//临时文件清理
			deleteTemFile(file);
		}


	}

	/**
	 * 根据url校验文件
	 * @param fileUrl
	 */
	private void validPicture(String fileUrl) {
		//校验非空
		ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");
		//校验url格式
		try {
			URL url = new URL(fileUrl);
		} catch (Exception e) {
			throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式错误");
		}
		//校验URL的协议
		ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://")
				, ErrorCode.PARAMS_ERROR, "仅支持http和https协议的文件地址");
		//发送HEAD请求验证文件是否存在
		HttpResponse execute = null;
		try {
			execute = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
			if (execute.getStatus() != HttpStatus.HTTP_OK) {
				return;
			}

			//文件存在，文件类型校验
			String contentType = execute.header("Content-Type");
			if (StrUtil.isNotBlank(contentType)) {
				//允许的图片类型
				List<String> allowFileType = List.of("image/jpeg", "image/png", "image/gif", "image/webp");
				ThrowUtils.throwIf(!allowFileType.contains(contentType), ErrorCode.PARAMS_ERROR, "文件类型错误");
			}
			//文件大小校验
			long contentLength = Long.parseLong(execute.header("Content-Length"));
			try {
				ThrowUtils.throwIf(contentLength > MAXSIZE, ErrorCode.PARAMS_ERROR, "文件大小不能超过2M");
			} catch (NumberFormatException e) {
				ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "文件大小格式异常");
			}
		} finally {
			if (execute != null) {
				execute.close();
			}
		}
	}

}
